<template>
  <div class="drawingMap-wrapper">
    <v-header title="黔东南-手绘地图"></v-header>

    <div id="container" style="height: 100%" :style="{height: mainHeight + 'px'}">
      <!-- <img class="bg" :src="imgs.mapBg"/> -->
      <img class="compass" :src="imgs.compass" width="50px" height="50px"/>

      <div class="play-voice" v-show="showPlayVoice">
        <img :src="imgs.voice" style="margin-right: 8px"/>
        <p v-if="selectProduct">正在为您播放"{{selectProduct.name.length > 9 ? selectProduct.name.substr(0, 8) + '...' : selectProduct.name}}"语音导览</p>
        <img :src="imgs.close" @click.stop="stopPlayVoice"/>
      </div>

    </div>

    <actionsheet v-model="showMap" :menus="menusMap" :show-cancel="showCancel" @on-click-menu="handleClickMenu"></actionsheet>
  </div>
</template>

<script>
import VHeader from '@/components/v-header/v-header'
import { Actionsheet } from 'vux'

import { isIphoneX, isIOS } from '@/assets/js/brower'
import axios from '@/api/axiosApi'
import nativeBridge from '@/assets/js/nativeBridge'
import { getDistance, distanceStr } from '@/assets/js/amap'
import { mapGetters, mapMutations } from 'vuex'
import imgs from './imgs.json'

export default {
  data() {
    return {
      imgs,
      showMap: false,
      showPlayVoice: false,
      showCancel: true,
      selectProduct: null,
      menusMap: {},
      scenicList: [],
      map: null
    }
  },
  components: {
    VHeader, Actionsheet
  },
  created () {
    this.mainHeight = window.innerHeight - 40 - 24
    if (isIphoneX()) {
      this.mainHeight = window.innerHeight - 40 - 34
    }

    const _self = this
    nativeBridge.getPosition(this, (arg) => {
      _self.setPosition([parseFloat(arg.longitude), parseFloat(arg.latitude)])
      _self.colDistance()
    })
  },
  mounted () {
    this.initMap()
    this._getScenicList()
  },
  destroyed () {
    if (this.map) {
      this.map.destroy()
    }

    nativeBridge.stopSpeechVoice()
  },
  computed: {
    ...mapGetters(['position'])
  },
  methods: {
    _getScenicList () {
      axios.get(this, '/v1/product', {
        type: 1
      }, (data) => {
        data.forEach(item => {
          if (item.feature == null || item.feature === '') {
            item.feature = '暂无特色简介'
          }
        })
        this.scenicList = data
        this.colDistance()
        this.createMarkers()
      })
    },
    initMap () {
      const exponed = 0.4
      const southWest = [107.299386, 25.30712]
      const northEast = [109.555051, 27.521601]
      const imageLayer = new AMap.ImageLayer({
        url: imgs.qdnDrawingMap,
        bounds: new AMap.Bounds(
          southWest,
          northEast
        )
      })
      this.map = new AMap.Map('container', {
        resizeEnable: true,
        zooms: [8, 11],
        zoom: 8,
        jogEnable: false,
        features: [],
        center: [108.529777, 26.429202],
        layers: [
          imageLayer
        ]
      })
      this.map.setLimitBounds(new AMap.Bounds(
        [southWest[0] - exponed, southWest[1] - exponed],
        [northEast[0] + exponed, northEast[1] + exponed]
      ))
      this.map.on('click', () => {
        this.map.clearInfoWindow()
      })
    },
    createMarkers () {
      // 创建一个信息窗体
      const infoWindow = new AMap.InfoWindow({
        isCustom: true,
        content: '',
        offset: new AMap.Pixel(6, -40)
      })
      this.scenicList.forEach((item, index) => {
        const scenicName = item.name.length > 9 ? item.name.substr(0, 8) + '...' : item.name
        const marker = new AMap.Marker({
          map: this.map,
          position: [parseFloat(item.longitude), parseFloat(item.latitude)],
          icon: new AMap.Icon({
            size: new AMap.Size(32, 45),
            imageSize: new AMap.Size(32, 45),
            image: this.getIconByType(item.imageTypes)
          }),
          label: {
            content: scenicName,
            offset: new AMap.Pixel(0, -23)
          },
          extData: item
        })
        marker.on('click', (e) => {
          // e.target.setAnimation('AMAP_ANIMATION_BOUNCE')
          // setTimeout(() => {
          //   e.target.setAnimation('AMAP_ANIMATION_NONE')
          // }, 2400)
          this.selectProduct = e.target.getExtData()
          infoWindow.setContent(this.createInfoWindow())
          infoWindow.open(this.map, e.target.getPosition())
        })
      })
    },
    createInfoWindow () {
      const data = this.selectProduct
      const scenicName = data.name.length > 15 ? data.name.substr(0, 14) + '...' : data.name
      const info = document.createElement('div')
      info.className = 'info'
      // 定义顶部标题
      const top = document.createElement('div')
      const titleD = document.createElement('div')
      const into = document.createElement('img')
      top.className = 'info-top'
      titleD.innerHTML = scenicName
      into.src = imgs.into
      top.onclick = () => {
        this.toScenic(data.id)
      }

      top.appendChild(titleD)
      top.appendChild(into)
      info.appendChild(top)

      // 定义中部内容
      const middle = document.createElement('div')
      middle.className = 'info-middle'
      const left = document.createElement('div')
      left.className = 'info-left'
      left.style.backgroundImage = `url(${data.thumbUrl})`
      const distance = document.createElement('p')
      distance.innerHTML = data.distance || '0Km'
      const right = document.createElement('div')
      right.className = 'info-right'
      const desc = document.createElement('p')
      desc.innerHTML = data.feature
      const voice = document.createElement('img')
      voice.src = imgs.btnVoice
      voice.onclick = this.toPlayVoice
      voice.style.marginRight = '8px'
      const navigate = document.createElement('img')
      navigate.src = imgs.btnNavigate
      navigate.onclick = this.toMap
      left.appendChild(distance)
      right.appendChild(desc)
      right.appendChild(voice)
      right.appendChild(navigate)
      middle.appendChild(left)
      middle.appendChild(right)
      info.appendChild(middle)

      return info
    },
    closeInfoWindow () {},
    getIconByType (type) {
      let icon = ''
      switch (type) {
        case '0':
          icon = imgs.mark1
          break
        case '1':
          icon = imgs.mark2
          break
        case '2':
          icon = imgs.mark3
          break
        case '3':
          icon = imgs.mark4
          break
        default:
          icon = imgs.mark1
          break
      }
      return icon
    },
    toScenic (id) {
      this.$router.push(`/scenic/${id}`)
    },
    toMap () {
      if (isIOS()) {
        window.webkit.messageHandlers.NativeMethod.postMessage({
          'methodName': 'openMapNavi',
          'latitude': this.selectProduct.latitude,
          'longitude': this.selectProduct.longitude})
      } else {
        // android
        this.menusMap = JSON.parse(window.android.isInstallByread())
        if (this.menusMap == null || Object.getOwnPropertyNames(this.menusMap).length === 1) {
          this.showCancel = false
          return
        }
        if (this.menusMap.baiDu === '2') {
          this.menusMap.baiDu = '百度地图'
        }
        if (this.menusMap.gaoDei === '1') {
          this.menusMap.gaoDei = '高德地图'
        }
        if (this.menusMap.tenXun === '3') {
          this.menusMap.tenXun = '腾讯地图'
        }
        this.showMap = true
      }
    },
    // 点击菜单跳转
    handleClickMenu (value) {
      if (value === 'baiDu') {
        window.android.makeUpMap(this.selectProduct.latitude, this.selectProduct.longitude, this.selectProduct.address, 2, 1, '')
      } else if (value === 'gaoDei') {
        window.android.makeUpMap(this.selectProduct.latitude, this.selectProduct.longitude, this.selectProduct.address, 1, 1, '')
      } else if (value === 'tenXun') {
        window.android.makeUpMap(this.selectProduct.latitude, this.selectProduct.longitude, this.selectProduct.address, 3, 1, '')
      }
    },
    colDistance() {
      if (this.position.length === 2 && this.scenicList.length > 0) {
        this.scenicList.forEach((item, index) => {
          item.distance = distanceStr(getDistance(this.position, [item.longitude, item.latitude]))
        })
      }
    },
    toPlayVoice () {
      this.showPlayVoice = true
      const _self = this
      nativeBridge.speechVoice(this.selectProduct.feature, () => {
        _self.showPlayVoice = false
      })
    },
    stopPlayVoice () {
      this.showPlayVoice = false
      nativeBridge.stopSpeechVoice()
    },
    ...mapMutations({
      setPosition: 'SET_POSITION'
    })
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'

.drawingMap-wrapper
  position fixed
  top 0
  left 0
  right 0
  bottom 0px
  z-index 101
  background #ffffff
.bg
  position absolute
  top 0
  left 0
  right 0
  bottom 0
  width 100%
  height 100%
.compass
  position absolute
  top 20px
  left 15px
.play-voice
  position absolute
  top 0
  left 0
  right 0
  height 30px
  padding 0 16px
  background rgba(0, 0, 0, 0.6)
  display flex
  justify-content space-between
  align-items center
  z-index 1000
  img
    height 13px
  p
    color #fff
    font-size 13px
    width calc(100% - 37px)
</style>


<style lang="stylus">
@import '~@/assets/css/variable.styl'
@import '~@/assets/css/mixins.styl'

.drawingMap-wrapper
  .amap-marker-label
    font-size 11px
    color #916112
    border-radius 3px
    border 1px solid #916112
    background rgba(255, 255, 255, 0.85)
    top -23px
    left 0
    transform translateX(-36%)
  .info
    background #fff
    width 285px
    border-radius 5px
    border 1px solid $color-border
    box-shadow 0 0 12px $color-border
    position relative
    .info-top
      display flex
      justify-content space-between
      align-items center
      padding 12px
      color #333
      font-size 15px
      border-bottom 1px solid $color-border
      line-height 1
      img
        height 14px
    .info-middle
      padding 12px
      display flex
      height 70px
      .info-left
        width 94px
        height 100%
        background-size cover
        background-position 50% 50%
        position relative
        border-radius 3px
        overflow hidden
        margin-right 10px
        p
          font-size 10px
          color #fff
          position absolute
          top 0
          left 0
          background rgba(0, 0, 0, 0.5)
          border-bottom-right-radius 5px
          line-height 1
          padding 5px 9px
      .info-right
        width calc(100% - 104px)
        p
          font-size 12px
          color #666
          line-height 1.3
          margin-bottom 10px
          height 29px
          no-wrap-n(2)
        img
          width calc(50% - 4px)
    &:before
      content ''
      display block
      position absolute
      top 100%
      left calc(50% - 7px)
      width 0
      height 0
      border-left 7px solid transparent
      border-right 7px solid transparent
      border-top 9px solid $color-border
    &:after
      content ''
      display block
      position absolute
      top calc(100% - 1px)
      left calc(50% - 7px)
      width 0
      height 0
      border-left 7px solid transparent
      border-right 7px solid transparent
      border-top 9px solid #fff
</style>
